package services

import (
	"context"
	"gitee.com/igolang/imoney/internal/common/keys"
	"gitee.com/igolang/imoney/internal/core/client"
	"gitee.com/igolang/imoney/internal/models/dao"
	"github.com/pkg/errors"
	"gorm.io/gorm"
	"time"
)

var Config = &config{}

type config struct{}

func (s *config) CleanCache(key string) {
	rk := keys.Config(key)
	client.Redis().Del(context.Background(), rk.Key)
}

func (s *config) SetCache(key string) string {
	rk := keys.Config(key)
	row, err := dao.SysConfig.Where(dao.SysConfig.ConfigKey.Eq(key)).Take()
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return ""
	}

	expired := rk.Expire
	value := ""
	if row != nil {
		value = row.ConfigValue
	} else {
		expired = 5 * time.Second
	}
	client.Redis().Set(context.Background(), rk.Key, value, expired)
	return value
}

func (s *config) Get(key string) string {
	rk := keys.Config(key)
	rc := client.Redis()
	ctx := context.Background()
	if rc.Exists(ctx, rk.Key).Val() > 0 {
		return rc.Get(ctx, rk.Key).Val()
	}

	return s.SetCache(key)
}
